/**
 * @(#)com.apache.Processor
 *
 * Copyright (c) 2014-2018 厦门民航凯亚有限公司
 *
 * DESC:
 *
 */
package com.apache;

import java.io.*;
import java.net.Socket;

/**
 *
 * @author fusf
 * @version 1.0  2015/6/29 0029
 */
public class Processor extends Thread{

    private Socket socket;

    private InputStream in;

    private PrintStream out;

    public final static String WEB_ROOT = "E:\\IT学习材料\\JEECG架构培训\\课程2_apache服务器\\作业\\hoshtml";

    public Processor(Socket socket) {
        this.socket = socket;
        try {
            in = socket.getInputStream();
            out = new PrintStream(socket.getOutputStream());
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        String fileName = parse(in);
        sendFile(fileName);
    }

    public String parse(InputStream in) {
        BufferedReader br = new BufferedReader((new InputStreamReader(in)));
        String fileName = "";
        try {
            String httpMessage = br.readLine();
            String [] content = httpMessage.split(" ");
           if(content.length!=3) {
               sendErrrorMessage(400,"调用错误");
           }
            //协议状态号，请求文件的名称、版本号
            System.out.println("协议状态号"+content[0]+"请求文件的名称"+content[1]+"版本号"+content[2]);
            fileName = content[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public void sendErrrorMessage(int errorCode ,String errorMessage) {
        out.println("HTTP/1.0"+errorCode+"  "+errorMessage);
        out.println("content-type:text/html");
        out.println();
        out.println("<html>");
        out.println("<title> Error Message");
        out.println("</title>");
        out.println("<body>");
        out.println("<h1>ErrorCode:"+errorCode+",errorMessage:"+errorMessage+"</h1>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendFile(String fileName) {
        File file = new File(Processor.WEB_ROOT+fileName);
        if(!file.exists()) {
            sendErrrorMessage(404,"File Not Found");
            return ;
        }

        try {
            InputStream in = new FileInputStream(file);
            byte content[] = new byte[(int) file.length()];
            in.read(content);
            out.println("HTTP/1.0 200 queryfile");
            out.println("content-length:"+content.length);
            out.println();
            out.write(content);
            out.close();
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
